package com.wind.cqboot.plugin;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wind.cqboot.consts.AlApiConst;
import com.wind.cqboot.utils.HttpUtil;

import cn.hutool.core.util.StrUtil;
import net.lz1998.cq.event.message.CQGroupMessageEvent;
import net.lz1998.cq.robot.CQPlugin;
import net.lz1998.cq.robot.CoolQ;
import net.lz1998.cq.utils.CQCode;

@Component
public class ContentCheckPlugin extends CQPlugin
{
    @Value("${alapi.token}")
    private String ALAPI_TOKEN;

    @Override
    public int onGroupMessage(CoolQ cq, CQGroupMessageEvent event)
    {
        String msg = event.getMessage();
        Long groupId = event.getGroupId();
        Long userId = event.getUserId();
        // 匹配过滤所有[]内的内容
        String regEx = "(\\[.+])+";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(msg);
        msg = m.replaceAll("").trim();
        if (StrUtil.isNotBlank(msg) && checkForbid(msg))
        {
            cq.deleteMsg(event.getMessageId());
            String content = " 该消息已违规，小依已撤回，骚年请自重";
            String result = CQCode.at(userId) + content;
            cq.sendGroupMsg(groupId, result, false);
            return MESSAGE_BLOCK;
        }
        // 继续执行下一个插件
        return MESSAGE_IGNORE;
    }

    // 检查是否违禁
    private boolean checkForbid(String text)
    {
        String[] whiteList = new String[]{"舔狗日记"};
        for (String str : whiteList)
        {
            if (str.equalsIgnoreCase(text))
            {
                return false;
            }
        }
        String result = HttpUtil.sendGet(StrUtil.format(AlApiConst.URL_CHECK_FORBID, ALAPI_TOKEN, text));
        if (StrUtil.isNotBlank(result))
        {
            JsonObject json = JsonParser.parseString(result).getAsJsonObject();
            if (json.get("code").getAsInt() == 200)
            {
                JsonObject data = json.get("data").getAsJsonObject();
                int spam = data.get("spam").getAsInt();
                if (spam == 1)
                {
                    return true;
                }
                else if (spam == 2)
                {
                    JsonArray review = data.getAsJsonArray("review");
                    for (JsonElement je : review)
                    {
                        float score = je.getAsJsonObject().get("score").getAsFloat();
                        if (score > 0.5)
                        {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}
